package com.zjt.web.api;

import com.zjt.entity.ClientUser;
import com.zjt.entity.VersionUpdate;
import com.zjt.service.IVersionUpdateService;
import com.zjt.service.user.IClientUserService;
import com.zjt.web.api.vo.base.StateVO;
import com.zjt.web.api.vo.base.UpdateVO;
import com.zjt.web.api.vo.base.UserVO;
import com.zjt.web.api.vo.request.CheckVersionReqVO;
import com.zjt.web.api.vo.request.StartInitReqVO;
import com.zjt.web.api.vo.response.CheckVersionRespVO;
import com.zjt.web.api.vo.response.StartInitRespVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by IntelliJ IDEA.
 * User: xueyanbeijing
 * Date: 12-8-14
 * Time: AM10:51
 * 程序首次初始化接口
 * 说明：userid,imei，email都能唯一定位一条记录  优先顺序：id-->imei-->email
 */

@Controller
@RequestMapping(value = "/api/start")
public class StartInitAPIController {
    private static Logger logger = LoggerFactory.getLogger(StartInitAPIController.class);
    private IClientUserService clientUserService;
    private IVersionUpdateService versionUpdateService;
    @Autowired
    public void setClientUserService(IClientUserService clientUserService) {
        this.clientUserService = clientUserService;
    }
    @Autowired
    public void setVersionUpdateService(IVersionUpdateService versionUpdateService) {
        this.versionUpdateService = versionUpdateService;
    }

    /**
     * 程序启动初始化,如果第一次登陆，则注册，第二次则刷新其记录
     * @param startInitReqVO
     * @return
     */
    @RequestMapping(value = {"init.json", ""})
    @ResponseBody
    public StartInitRespVO init(StartInitReqVO startInitReqVO) {
        logger.info("/api/start/init request parms = " + startInitReqVO.toString());
        //TODO 进行请求参数的解析
        boolean doFlag = false;
        ClientUser clientUser = null;
        ClientUser clientUserToVO = null;
        try
        {
            String userName = "";
           if (startInitReqVO.getUserId()!=null)
                userName = startInitReqVO.getUserId().toString();
           if (userName.length()>0)//存在
            {
                clientUser = this.clientUserService.getClientUserById(startInitReqVO.getUserId());
                if (clientUser!=null)    //todo id存在
                {
                    if (clientUser.getPasswd()!=null&&startInitReqVO.getPasswd()!=null&&clientUser.getPasswd().equalsIgnoreCase(startInitReqVO.getPasswd()))
                            doFlag = true;
                        else
                            logger.error("登陆失败，密码错误");
                    //不管登陆成功与否，都将同步更新用户信息
                    try
                    {
                        clientUserToVO = this.clientUserService.updateClientUser(startInitReqVO.getUserId(),startInitReqVO.getNickName(),startInitReqVO.getEmail(),clientUser.getPasswd(),
                                startInitReqVO.getMdn(),clientUser.getSex(),startInitReqVO.getVersion(),startInitReqVO.getPlatform(),startInitReqVO.getImei());
                        doFlag = true;//
                    }catch (Exception e){
                        logger.error("更新资料异常");
                    }
                } // id 未找到    clientUser == null
                else
                {
                    //TODO 开始通过imei找
                    clientUser = this.clientUserService.getClientUserByImei(startInitReqVO.getImei().trim());
                   if (clientUser==null)
                   {
                       try{
                           clientUserToVO = this.clientUserService.registerClientUser(startInitReqVO.getNickName(),startInitReqVO.getEmail(),
                                   startInitReqVO.getPasswd(),startInitReqVO.getMdn(),null,startInitReqVO.getVersion(),startInitReqVO.getPlatform(),
                                   startInitReqVO.getImei());
                       }catch (Exception e){
                       }
                   }else  clientUserToVO = clientUser;
                    doFlag = true;
                }
            }else//注册   userid不存在
            {
                try
                {
                    clientUser = this.clientUserService.getClientUserByImei(startInitReqVO.getImei());
                }catch (Exception ee)
                {
                }
                if (clientUser==null)
                {
                    try{
                        clientUserToVO = this.clientUserService.registerClientUser(startInitReqVO.getNickName(),startInitReqVO.getEmail(),
                                startInitReqVO.getPasswd(),startInitReqVO.getMdn(),null,startInitReqVO.getVersion(),startInitReqVO.getPlatform(),
                                startInitReqVO.getImei());
                        doFlag = true;
                    }catch (Exception e1){
                        logger.error("注册失败");
                    }
                }else //通过imei找到老用户
                {
                    doFlag = true;
                    clientUserToVO = clientUser;
                }

            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error("初始化协议接口失败");
        }

        StartInitRespVO startInitRespVO = new StartInitRespVO();
        //TODO 进行业务逻辑的处理 ， 封装应答数据
        try
        {
            VersionUpdate versionUpdate = this.versionUpdateService.checkVersionUpdate(startInitReqVO.getVersion(),startInitReqVO.getPlatform());
            if (versionUpdate!=null)//有版本更新
            {
                UpdateVO updateVO = new UpdateVO();
                updateVO.setTitle(versionUpdate.getVersionString());
                updateVO.setUrl(versionUpdate.getUrl());
                updateVO.setDesc(versionUpdate.getDescription());
                startInitRespVO.setUpdateVO(updateVO);
                logger.info("更新版本需要更新了，updateVO="+updateVO.toString());
            } else startInitRespVO.setUpdateVO(null);
            startInitRespVO.setStateVO(new StateVO());
            if (doFlag)
            {
                UserVO userVO = new UserVO();
               if (clientUserToVO!=null)
               {
                   userVO.setImei(clientUserToVO.getImei());
                   userVO.setPasswd(clientUserToVO.getPasswd());
                   userVO.setPlatform(clientUserToVO.getPlatform());
                   userVO.setUserId(clientUserToVO.getId()); //新注册的用户id
                   userVO.setVersion(clientUserToVO.getVersion());
                   userVO.setEmail(clientUserToVO.getEmail());
                   userVO.setMdn(clientUserToVO.getMdn());
                   userVO.setSex(clientUserToVO.getSex());
                   userVO.setNickName(clientUserToVO.getNickName());
                   logger.info("clientUserToVO:"+clientUserToVO.toString());
               }
                startInitRespVO.setUserVO(userVO);
            }
        }catch (Exception e1){}
        logger.info("/api/start/init response result = " + startInitRespVO.toString());
        return startInitRespVO;
    }
    /**
     * 版本检查，用于关于页面，返回需要更新版下载信息
     * @param checkVersionReqVO
     * @return
     */
    @RequestMapping(value = {"checkVersion.json", ""})
    @ResponseBody
    public CheckVersionRespVO checkVersion(CheckVersionReqVO checkVersionReqVO){
        logger.info("/api/start/checkVersion request param = " + checkVersionReqVO.toString());
        CheckVersionRespVO checkVersionRespVO = new CheckVersionRespVO();
        if (checkVersionReqVO!=null)
        {
            VersionUpdate versionUpdate = null;
            StateVO stateVO = new StateVO();
            if (checkVersionReqVO.getVersion()!=null&&checkVersionReqVO.getVersion().length()>0)
            {
                try
                {
                    versionUpdate = this.versionUpdateService.checkVersionUpdate(checkVersionReqVO.getVersion(),checkVersionReqVO.getPlatform());
                    if (versionUpdate!=null)
                    {
                        UpdateVO updateVO = new UpdateVO();
                        updateVO.setDesc(versionUpdate.getDescription());
                        updateVO.setTitle(versionUpdate.getVersionString());
                        updateVO.setUrl(versionUpdate.getUrl());
                        checkVersionRespVO.setUpdateVO(updateVO);
                        checkVersionRespVO.setStateVO(stateVO);
                    }else
                    {
                        stateVO.setMsg("当前已经是最新版本");
                        stateVO.setCode(0);
                        checkVersionRespVO.setStateVO(stateVO);
                        checkVersionRespVO.setUpdateVO(null);
                    }
                }catch (Exception e){}
            }
        }
        logger.info("/api/start/checkVersion response result = " + checkVersionRespVO.toString());
        return checkVersionRespVO;
    }
}
